//
//  userstool.m
//  xhtios1.0
//
//  Created by hlt on 15/7/10.
//  Copyright (c) 2015年 hlt. All rights reserved.
//

#import "userstool.h"

@implementation userstool


+(NSString *)getjsonnsstring:(NSDictionary *)InputBody jiemifangshi:(BOOL) jiemi
{

    NSDictionary *dicttt = InputBody;
    //将字典转化为json格式的字符串InputBody的数据
    NSString *getjson =[SetBase64andMd5  tojson: dicttt];
    
     Account *acc=[[AccountTool sharedAccountTool ]currentAccount];
    //使用3DES进行加密
    NSString *key;
    if (jiemi) {
        //使用初始密码
        key=kxhtkey;
            }else
    {
        key=acc.xhtpwd;   //使用新密码

    }
    
    NSString *jsonkey=[Set3Des TripleDES:getjson deskey:key encryptOrDecrypt:kCCEncrypt];
    
    
    //这个是设置tag参数的
    NSString *strtag=[jsonkey stringByAppendingString:kVerifyCode];  //首先拼接上客户端身份校验信码
    NSString *tagstr=[SetBase64andMd5 md5:strtag];   //进行MD5加密
    
    
    //设置WorkGuid参数的值使用了正式密钥加密的
    NSString *WorkGuid= [Set3Des TripleDES:acc.WorkGuid deskey:key  encryptOrDecrypt:kCCEncrypt];

    //最终上传字典
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:kClientCode,@"ClientCode",WorkGuid,@"WorkGuid",jsonkey,@"InputBody",tagstr,@"Tag",nil];
    //将最终的字典转化为json格式的字符串
    NSString *getjson1 =[SetBase64andMd5  tojson: dict];
    
    return getjson1;

   
}

//为了配合使用webservice
+(NSDictionary *) getxmldict:(id) responseObject
{
    
    NSString *xmlString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    // 使用XMLReader，将xml数据解析为字典格式（请看XMLReader类中的方法）
    NSError *error = nil;
    NSDictionary *xmlDic = [XMLReader dictionaryForXMLString:xmlString error:&error];
    NSLog(@"%@",xmlDic);
    //获取到返回的json格式的字符串
    NSString* json= xmlDic[@"string"][@"text"];
    //将json格式的字符串转换为字典
    NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    return dic;
}


//将被加密的字符串解密并且转换为字典
+(NSDictionary *) getjiemidict:(NSString *) desstring jiemifangshi:(BOOL) jiemi
{
    Account *acc=[[AccountTool sharedAccountTool ]currentAccount];
    //使用3DES进行加密
    NSString *key;
    if (jiemi) {
        //使用初始密码
        key=kxhtkey;
    }else
    {
          key=acc.xhtpwd;   //使用新密码
       
    }
    
    
    
    //调用3DES解密数据，如果已经获取过密钥，就用获取的密钥解密，否则使用初始密钥解密
    NSString *jsonkey=[Set3Des TripleDES:desstring deskey:key encryptOrDecrypt:kCCDecrypt];
    NSLog(@"%@??%@",key,jsonkey);
    
    NSData *jsonData1 = [jsonkey dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err1;
    NSDictionary *dicc = [NSJSONSerialization JSONObjectWithData:jsonData1
                                                         options:NSJSONReadingMutableContainers
                                                           error:&err1];
    
    
    
    return  dicc;

}

+(void) jianchakey
{
    
    //先检查时间有没有超过一天没有则不执行请求
    NSDateFormatter *fommater=[[NSDateFormatter alloc] init];
    [fommater setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *now= [NSDate new];
    NSString *str= [fommater stringFromDate:now];
    NSLog(@"%@",str);
    
    
    
    
    //删除一次数据
    //清空保存的用户数据
//    [[AccountTool sharedAccountTool] signOut:[AccountTool sharedAccountTool].currentAccount];
    
    
    
    Account *acc =[[AccountTool sharedAccountTool] currentAccount];
    //没有则创建一个acc
    if (!acc) {
        
        acc=[[Account alloc]init];
        acc.uid=@"96696021";
        acc.cardType=@"";
        acc.custIdent=@"";
        acc.cardNo=@"";
        acc.custName=@"";
        acc.custIType=@"";
        acc.custPhone=@"";
        acc.custAddr=@"";
        acc.custSex=@"";
        acc.custFlag=@"";
        acc.modiDate=@"";
        acc.pwd=@"";
        acc.YKTCardBalance=@"";
        acc.YKTCardJF=@"";
        acc.HaveYKTCard=@"";
        acc.NickName=@"";
        acc.HeadImg=@"";
        acc.WeXinId=@"";
        acc.Email=@"";
        acc.CheckTime=@"";
        acc.xhtpwd=@"";
        acc.WorkGuid=@"";
        [[AccountTool sharedAccountTool] addAccounts:acc];
        
    }
    
    NSString *nowdate= acc.CheckTime;
    NSString *str11;
    if (![nowdate isEqual:@""]) {
        str11=[nowdate substringWithRange:NSMakeRange(0,10)];
        NSLog(@"%@??%@",acc.CheckTime,acc.xhtpwd);
        
    }
    
    
    NSDateFormatter *fommater1=[[NSDateFormatter alloc] init];
    [fommater1 setDateFormat:@"yyyy-MM-dd"];

    NSDate *mydate= [fommater1 dateFromString:str11];
    NSTimeInterval timenum=[now timeIntervalSinceDate:mydate];
    NSLog(@"%f",timenum);
    if (3600*24<timenum||!mydate) {
        
        //如果没有登录
        
        acc.xhtpwd=@"";
        
        [[AccountTool sharedAccountTool] addAccounts:acc];
        
        //签到获取密钥的请求函数
        AFHTTPRequestOperationManager *m1 = [[AFHTTPRequestOperationManager alloc] init];
        
        // AFHTTPResponseSerializer不使用解析，即返回的为NSData类型数据，如果使用AFXMLParserResponseSerializer 解析会比较麻烦，所以会在后面使用第三方的XML解析(XMLReader)
        m1.responseSerializer = [AFHTTPResponseSerializer serializer];
        //    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"ishot",@"1",@"start",@"5",@"end",nil];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"002",@"ClientCode",@"1w/sLjVpzSQ=",@"UserId",@"u/kEhAoAV0AxPhsKwYTthQ==",@"UserPwd",nil];
        
        NSString *getjson =[SetBase64andMd5  tojson: dict];
        
//        NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:getjson,@"InputPara",nil];
        
        //    NSString *url=[NSString stringWithFormat:@"%@%@",xhturl,shopmerclist];
        NSString *url=[NSString stringWithFormat:@"%@%@&%@=%@",xhturl,xhtmiyue,@"InputPara",getjson];
        
        NSLog(@"%@",url);
        //将url转换一下格式，否则请求的格式就不兼容
        url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        AFHTTPRequestOperation *op1 = [m1 GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
                                       {
                                           
                                           //将XML数据转换为我们需要的字典
                                           NSDictionary *dic = [userstool getxmldict:responseObject];
                                           NSLog(@"%@",dic[@"RtnMsg"]);
                                           
                                           //调用3DES解密数据，如果已经获取过密钥，就用获取的密钥解密，否则使用初始密钥解密
                                           NSDictionary *dicc=[userstool getjiemidict:dic[@"RtnMsg"] jiemifangshi:YES];
                                           
                                           Account *acc =[[AccountTool sharedAccountTool] currentAccount];
                                           //                                           Account *acc=[[Account alloc]init];
                                           //将key等数据缓存到本地
                                           NSLog(@"%@",dicc);
                                           acc.CheckTime=dicc[@"CheckTime"];
                                           acc.WorkGuid=dicc[@"WorkGuid"];
                                           acc.xhtpwd=dicc[@"DesKey"];
                                           //这一句就是将新的account添加到沙盒里面去
                                           [[AccountTool sharedAccountTool] addAccounts:acc];
                                           
                                       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                           
                                           UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"请求网络失败"   message:@"请重试" delegate:nil cancelButtonTitle:@"好" otherButtonTitles: nil];
                                           [alert show];
                                           
                                           
                                       }];
        [op1 start];
        
        
        
    }
   

    

}








@end
